package cn.kimming.wms.web.interceptor;

import java.lang.reflect.Method;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import cn.kimming.wms.anno.RequiredPermission;
import cn.kimming.wms.domain.Employee;
import cn.kimming.wms.domain.JsonMsg;
import cn.kimming.wms.util.JsonUtils;
import cn.kimming.wms.util.PermissionUtils;
import cn.kimming.wms.util.UserContext;

/**
 * 权限检查拦截器
 * @author Kimming
 *
 */
public class SecurityInterceptor extends AbstractInterceptor{

	private static final long serialVersionUID = 7269352961230383375L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String methodName = invocation.getProxy().getMethod();
		Method method = invocation.getAction().getClass().getDeclaredMethod(methodName);
		RequiredPermission rp = method.getAnnotation(RequiredPermission.class);
		//1.判断当前操作方法上是否有权限要求标签,有则GOTO2,没有则放行
		if (rp == null) {
			return invocation.invoke();
		}
		Employee user = UserContext.getUser();
		//2.判断当前用户是否为root,不是则GOTO3,是则放行
		if (user.isAdmin()) {
			return invocation.invoke();
		}
		Set<String> permissions = UserContext.getPemissions();
		//3.判断当前用户是否拥有此权限表达式,没有则跳转nopermission页面,有则放行
		if (permissions.contains(PermissionUtils.buildExpression(method))) {
			return invocation.invoke();
		}
		
		//对于要求返回视图的方法,返回nopermission视图
		if ("execute".equals(methodName)) {
			return "nopermission";
		}
		//对于ajax请求,返回JsonMsg消息对象
		HttpServletResponse resp = ServletActionContext.getResponse();
		JsonUtils.putJSON(resp, new JsonMsg(false, "权限不足, 操作失败!"));
		return Action.NONE;
	}

}
